#include "server.h"
#include "ui_server.h"
#include <QMessageBox>
#include <QTcpServer>
#include <QTcpSocket>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QTableWidget>
#include <QStringList>
#include <QDebug>

server::server(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::server)
{
    ui->setupUi(this);

    // 创建一个TCP服务器
    server1 = new QTcpServer(this);
    connect(server1, &QTcpServer::newConnection, this, &server::newConnection);

    // 在特定端口上开始监听
    if (!server1->listen(QHostAddress::Any, 1234)) {
        QMessageBox::critical(this, tr("Server Error"), tr("无法启动服务器：%1").arg(server1->errorString()));
        return;
    }

    // 打开SQLite数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("/home/gjd/Qt/Data.db");
    if (!db.open()) {
        QMessageBox::critical(this, tr("Database Error"), tr("无法打开数据库"));
        return;
    }

    // 创建 tableWidget 并设置列数
    tableWidget = new QTableWidget(this);
    tableWidget->setColumnCount(3);

    // 设置列标签
    QStringList headers;
    headers << "用户名" << "IP" << "端口";
    tableWidget->setHorizontalHeaderLabels(headers);

    // 设置 tableWidget 的位置和大小
    tableWidget->setGeometry(50, 90, 301, 191);

    qDebug() << "服务器已启动，等待客户端连接...";
}

server::~server()
{
    delete ui;
}

void server::newConnection()
{
    // 当有新连接建立时
    QTcpSocket *clientSocket = server1->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, [this, clientSocket]() {
        onReadyRead(clientSocket);
    });

    qDebug() << "有客户端连接";
}

void server::onReadyRead(QTcpSocket *clientSocket)
{
    // 从客户端读取传入的数据
    QByteArray data = clientSocket->readAll();
    QString message = QString::fromUtf8(data);

    QStringList parts = message.split("\n", QString::SkipEmptyParts);

    QString requestType = parts[0];

    qDebug() << "获取信息";

    if (requestType == "REGISTER") {
        QString username = parts[1];
        QString password = parts[2];
        QString problem = parts[3];
        QString answer = parts[4];
        // 检查用户名是否已存在
        QSqlQuery query;
        query.prepare("SELECT Username FROM Users WHERE Username = ?");
        query.bindValue(0, username);
        if (query.exec() && query.next()) {
            // 用户名已存在
            sendResponse(clientSocket, "REGISTER_FAIL");
        } else {
            // 用户名不存在，进行注册
            query.prepare("INSERT INTO Users (Username, Password, Problem, Answer) VALUES (?, ?, ?, ?)");
            query.bindValue(0, username);
            query.bindValue(1, password);
            query.bindValue(2, problem);
            query.bindValue(3, answer);
            if (query.exec()) {
                // 注册成功
                sendResponse(clientSocket, "REGISTER_SUCCESS");
            } else {
                // 注册失败
                sendResponse(clientSocket, "REGISTER_FAIL");
            }
        }

    } else if (requestType == "LOGIN") {
        QString username = parts[1];
        QString password = parts[2];
        // 检查用户名和密码是否匹配
        QSqlQuery query;
        query.prepare("SELECT Username FROM Users WHERE Username = ? AND Password = ?");
        query.bindValue(0, username);
        query.bindValue(1, password);
        if (query.exec() && query.next()) {
            // 用户名和密码匹配
            sendResponse(clientSocket, "LOGIN_SUCCESS\nNONE\n");
        } else {
            // 用户名和密码不匹配
            sendResponse(clientSocket, "LOGIN_FAIL\nNONE\n");
        }
    }  else if (requestType == "FORGET") {
        QString username = parts[1];
        QString answer = parts[2];
        QString password = parts[3];
        // 检查用户名和答案是否匹配
        QSqlQuery query;
        query.prepare("SELECT Username FROM Users WHERE Username = ? AND Answer = ?");
        query.bindValue(0, username);
        query.bindValue(1, answer);
        if (query.exec() && query.next()) {
            // 用户名和答案匹配
            QSqlQuery query;
            query.prepare("UPDATE Users SET Password = ? WHERE Username = ?");
            query.bindValue(0, password);
            query.bindValue(1, username);

            if (query.exec()) {
                sendResponse(clientSocket, "FORGET_SUCCESS");
            } else {
                sendResponse(clientSocket, "FORGET_FAIL");
            }
        } else {
            // 用户名和答案不匹配
            sendResponse(clientSocket, "FORGET_FAIL");
        }
    } else if (requestType == "PROBLEM") {
        QString username = parts[1];

        QSqlQuery query;
        query.prepare("SELECT Problem FROM Users WHERE Username = ?");
        query.bindValue(0, username);

        if (query.exec() && query.next()) {
            QString problem = query.value(0).toString();
            QString message = "PROBLEM_SUCCESS\n";
            message += problem + "\n";
            sendResponse(clientSocket, message.toUtf8());
        } else {
            sendResponse(clientSocket, "PROBLEM_FAIL\nNONE\n");
        }
    } else if (requestType == "LOGIN_IN") {
        QString username = parts[1];

        // 获取客户端的用户名、IP 和端口信息
        QString ip = clientSocket->peerAddress().toString();
        QString port = QString::number(clientSocket->peerPort());

        // 将信息添加到 tableWidget
        int row = tableWidget->rowCount();
        tableWidget->insertRow(row);
        tableWidget->setItem(row, 0, new QTableWidgetItem(username));
        tableWidget->setItem(row, 1, new QTableWidgetItem(ip));
        tableWidget->setItem(row, 2, new QTableWidgetItem(port));

        for (const ClientInfo& info : clients) {
            sendResponse(info.clientSocket, "LOGIN_IN\n" + username);
        }

        QString message = "LOGIN_IN2\n";
        for (const ClientInfo& info : clients) {
            message += info.username + "\n";
        }
        sendResponse(clientSocket, message);

        ClientInfo info;
        info.username = username;
        info.clientSocket = clientSocket;
        clients.append(info);

    } else if (requestType == "CLOSE") {
        QString username = parts[1];

        // 遍历表格的每一行
        for (int row = 0; row < tableWidget->rowCount(); ++row) {
            QTableWidgetItem *item = tableWidget->item(row, 0); // 获取第一列的单元格
            if (item && item->text() == username) { // 如果找到了要删除的用户名
                tableWidget->removeRow(row); // 删除整行
                break; // 找到并删除后，退出循环
            }
        }

        for (int i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                clients.removeAt(i);
                break;
            }
        }

        for (const ClientInfo& info : clients) {
            sendResponse(info.clientSocket, "CLOSE\n" + username);
        }
    } else if (requestType == "CLOSE2") {
        QString username = parts[1];

        // 遍历表格的每一行
        for (int row = 0; row < tableWidget->rowCount(); ++row) {
            QTableWidgetItem *item = tableWidget->item(row, 0); // 获取第一列的单元格
            if (item && item->text() == username) { // 如果找到了要删除的用户名
                tableWidget->removeRow(row); // 删除整行
                break; // 找到并删除后，退出循环
            }
        }

        for (int i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                clients.removeAt(i);
                break;
            }
        }

        for (const ClientInfo& info : clients) {
            sendResponse(info.clientSocket, "CLOSE\n" + username);
        }

        sendResponse(clientSocket, "CLOSE2\nNONE\n");
    } else if (requestType == "PEOPLE") {
        int rowCount = tableWidget->rowCount();
        QString rowCountStr = QString::number(rowCount);
        QString message = "PEOPLE\n";
        message += rowCountStr;
        sendResponse(clientSocket, message.toUtf8());
    } else if (requestType == "CHAT2") {
        QString username = parts[1];
        QString message = parts[2];
        QString m_username = parts[3];

        for (int i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                sendResponse(clients[i].clientSocket, "CHAT2\n" + m_username + "\n" + message + "\n");
                break;
            }
        }
    } else if (requestType == "CHAT1") {
        QString message = parts[1];
        QString m_username = parts[2];

        for (int i = 0; i < clients.size(); ++i) {
            if (clients[i].username != m_username) {
                sendResponse(clients[i].clientSocket, "CHAT1\n" + m_username + "\n" + message + "\n");
            }
        }
    } else if (requestType == "TIREN") {
        QString username = parts[1];
        if (clients[0].username == username) {
            sendResponse(clientSocket, "TIREN_SUCCESS\nNONE\n");
        } else {
            sendResponse(clientSocket, "TIREN_FAIL\nNONE\n");
        }
    } else if (requestType == "JINYAN") {
        QString username = parts[1];
        if (clients[0].username == username) {
            sendResponse(clientSocket, "JINYAN_SUCCESS\nNONE\n");
        } else {
            sendResponse(clientSocket, "JINYAN_FAIL\nNONE\n");
        }
    } else if (requestType == "JIEJIN") {
        QString username = parts[1];
        if (clients[0].username == username) {
            sendResponse(clientSocket, "JIEJIN_SUCCESS\nNONE\n");
        } else {
            sendResponse(clientSocket, "JIEJIN_FAIL\nNONE\n");
        }
    } else if (requestType == "TIREN2") {
        QString username = parts[1];
        int i;
        for (i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                sendResponse(clients[i].clientSocket, "TIREN2\nNONE\n");
                sendResponse(clientSocket, "TIREN2_SUCCESS\nNONE\n");
                break;
            }
        }
        if (i==clients.size()) {
            sendResponse(clientSocket, "TIREN2_FAIL\nNONE\n");
        }
    } else if (requestType == "JINYAN2") {
        QString username = parts[1];
        int i;
        for (i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                sendResponse(clients[i].clientSocket, "JINYAN2\nNONE\n");
                sendResponse(clientSocket, "JINYAN2_SUCCESS\nNONE\n");
                break;
            }
        }
        if (i==clients.size()) {
            sendResponse(clientSocket, "JINYAN2_FAIL\nNONE\n");
        }
    } else if (requestType == "JIEJIN2") {
        QString username = parts[1];
        int i;
        for (i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                sendResponse(clients[i].clientSocket, "JIEJIN2\nNONE\n");
                sendResponse(clientSocket, "JIEJIN2_SUCCESS\nNONE\n");
                break;
            }
        }
        if (i==clients.size()) {
            sendResponse(clientSocket, "JIEJIN2_FAIL\nNONE\n");
        }
    } else if (requestType == "WENJIAN") {
        QString username = parts[1];
        QString fileName = parts[2];
        int count = 0;
        int index = -1;
        // 找到第三个 "\n" 的位置
        while (count < 3) {
            index = message.indexOf("\n", index + 1);
            if (index == -1) {
                // 如果找不到第三个 "\n"，处理错误或者跳出循环
                break;
            }
            count++;
        }
        QString file1;
        if (index != -1) {
            // 使用 mid() 函数提取第三个 "\n" 后的内容
            file1 = message.mid(index + 1);
        }

        int i;
        for (i = 0; i < clients.size(); ++i) {
            if (clients[i].username == username) {
                sendResponse(clients[i].clientSocket, "WENJIAN\n" + fileName);
                sendResponse(clients[i].clientSocket, file1);
                sendResponse(clientSocket, "WENJIAN_SUCCESS\nNONE\n");
                break;
            }
        }
        if (i==clients.size()) {
            sendResponse(clientSocket, "WENJIAN_FAIL\nNONE\n");
        }
    }
}

void server::sendResponse(QTcpSocket *clientSocket, const QString &responseType)
{
    // 向客户端发送响应
    QByteArray responseData;
    QDataStream responseStream(&responseData, QIODevice::WriteOnly);
    responseStream << responseType;
    clientSocket->write(responseData);

    qDebug() << "发送响应";
}
